package com.cloud.fim.gate.bean;

import com.cloud.fim.common.Bootstrap;
import com.cloud.fim.gate.handler.LoginHandler;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.stereotype.Component;

/**
 * <p></p>
 *
 * @author GaoShuangWen
 * @since 2019-12-05 20:53
 */
@Component
public class ServerBootstrap implements Bootstrap {
    @Override
    public void start() {
        EventLoopGroup boss = new NioEventLoopGroup(1);
        EventLoopGroup work = new NioEventLoopGroup();
        io.netty.bootstrap.ServerBootstrap bootstrap =new io.netty.bootstrap.ServerBootstrap();

        try {
            bootstrap
                    .group(boss,work)
                    .channel(NioServerSocketChannel.class)
                    .localAddress(8080)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch){
                            // 管理pipeline中的Handler
                            ChannelPipeline pipeline = ch.pipeline();
                         /*   ch.pipeline().addLast("decoder", new DataPacketDecoder());
                            ch.pipeline().addLast("encoder", new DataPacketEncoder());*/
                            pipeline.addLast(new LoginHandler());
                        }
                    });
            // 绑定端口，并且同步获取结果
            ChannelFuture channelFuture = bootstrap.bind().sync();
            channelFuture.addListener(future -> {
             /*  // 注册命名服务
                InetSocketAddress socketAddress = (InetSocketAddress) channelFuture.channel().localAddress();
                ImServerInstance node = new ImServerInstance(InetAddress.getLocalHost().getHostAddress(),String.valueOf(socketAddress.getPort()));
                NameService.getInst().registeredNode(node);
                ImServerInstanceFactory.add(node);*/
            });
            // 阻塞线程 直到channel关闭
            ChannelFuture closeFuture = channelFuture.channel().closeFuture();
            closeFuture.sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            // netty 优雅关闭
            boss.shutdownGracefully();
            work.shutdownGracefully();
        }

    }
}
